﻿using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto.Generators;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Umi.Crypto.Abstraction.Keys;
using Umi.Web.Metadatas.Attributes;

namespace Umi.Web.Crypto.Crypto.Rsa
{
    [Service("rsaKeyCreator", Scoped = ServiceScoped.Single)]
    public class RsaKeyCreator : IKeyParameterCreator
    {
        public Umi.Crypto.Abstraction.Keys.KeyParameter Create(string key)
        {
            if (key == null)
                throw new ArgumentNullException(nameof(key));
            using (StringReader reader = new StringReader(key))
            {
                PemReader pem = new PemReader(reader);
                object keyObj = pem.ReadObject();
                if (keyObj is ICipherParameters pk)
                    return new RsaKeyParameter(pk);
                if (keyObj is AsymmetricCipherKeyPair keyPair)
                    return new RsaKeyParameter(keyPair.Private);
            }
            throw new ArgumentException("argument format unhandled");
        }

        public Umi.Crypto.Abstraction.Keys.KeyParameter RandomKey()
        {
            RsaKeyGenerationParameters generationParameters = new RsaKeyGenerationParameters(BigInteger.Three, new SecureRandom(), 4096, 25);
            RsaKeyPairGenerator generator = new RsaKeyPairGenerator();
            generator.Init(generationParameters);
            AsymmetricCipherKeyPair pair = generator.GenerateKeyPair();
            return new RsaKeyParameter(pair.Private);
        }
    }

    public sealed class RsaKeyParameter : Umi.Crypto.Abstraction.Keys.KeyParameter
    {

        public ICipherParameters Parameters { get; }
        public RsaKeyParameter(ICipherParameters parameters)
        {
            Parameters = parameters;
        }
    }
}
